<template>
  <div class="approval-form-page pl-3">
    <div class="approval-form">
      <BasicForm @register="registerForm" ref="formRef" />

      <div v-if="processInstanceId" class="discuss-section">
        <VBlaDiscuss
          ref="discussRef"
          :theme="appTheme"
          :locale="locale"
          :processInstanceId="processInstanceId"
          :innerStyle="{ borderRadius: '8px' }"
        />
      </div>
    </div>

    <div v-if="processInstanceId" class="approval-components">
      <VBlaDecision ref="decisionRef" :theme="appTheme" :taskId="taskId" :locale="locale" :hideUrge="false" :decisionClick="decisionClick" />
      <VBlaRecordPreview
        ref="recordPreviewRef"
        :theme="appTheme"
        class="record-preview-container"
        :locale="locale"
        :processInstanceId="processInstanceId"
        :previewHeight="500"
        :widgetsShowConfig="displayConfig"
        @view-chart="handleViewChart"
      />
    </div>
  </div>
</template>

<script lang="ts">
  import { BasicForm, useForm, useFormPermit } from '/@/components/Form';
  import { propTypes } from '/@/utils/propTypes';
  import { computed, defineComponent, inject, onMounted, ref } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { getBpmFormSchema } from './ServiceRecord.data';
  import { saveOrUpdate } from './ServiceRecord.api';
  import { useRoute } from 'vue-router';
  import { getToken } from '/@/utils/auth';
  import { VBlaDiscuss, VBlaDecision, VBlaRecordPreview } from '@byteluck/approval-wc-widgets-desktop';
  import { useTabs } from '/@/hooks/web/useTabs';

  export default defineComponent({
    name: 'ServiceRecordApproval',
    components: {
      BasicForm,
      VBlaDiscuss,
      VBlaDecision,
      VBlaRecordPreview,
    },
    props: {
      formData: propTypes.object.def({}),
      formBpm: propTypes.bool.def(true),
      taskId: '',
    },
    setup(props) {
      const token = getToken();
      const { close: closeTab } = useTabs();
      const appTheme = inject('appTheme');
      window.approvalConfig.headers = {
        authorization: token,
        'x-access-token': token,
      };
      const route = useRoute();
      const displayConfig = ref({
        flow_virtual: 'DISPLAY',
        approval_record: 'DISPLAY',
      });
      const processInstanceId = ref('');
      const taskId = ref(route.query.taskId);

      const locale = ref('zh');

      let permitEnum = ref([]);
      let { judgeIf, judeRequired, judgeRead } = useFormPermit(permitEnum);
      const [registerForm, { setFieldsValue, setProps, clearValidate }] = useForm({
        labelWidth: 150,
        schemas: getBpmFormSchema(props.formData, { judgeIf, judeRequired, judgeRead }),
        showActionButtonGroup: false,
        baseColProps: { span: 6 },
      });

      onMounted(() => {
        clearValidate();
      });

      const formDisabled = computed(() => {
        if (props.formData.disabled === false) {
          return false;
        }
        return false;
      });

      const formRef = ref();
      async function handleSubmit() {
        try {
          return await formRef.value.validate();
        } catch (e) {
          return Promise.reject('表单校验失败');
        }
      }

      const runProcessUrl = '/servicerecorddemo/serviceRecord/runProcess';
      const queryByIdUrl = '/servicerecorddemo/serviceRecord/queryByTaskId';
      async function initFormData() {
        let params;
        if (props.taskId !== undefined) {
          params = { taskInstanceId: props.taskId };
          taskId.value = props.taskId;
        } else {
          params = { taskInstanceId: taskId.value };
        }
        const res = await defHttp.post({ url: queryByIdUrl, params });
        processInstanceId.value = res.processParam?.processInstanceId;
        permitEnum.value = res.permissions;
        await setFieldsValue({ ...res.data });
        await setProps({ disabled: formDisabled.value });
      }

      initFormData();

      const decisionClick = async (evt) => {
        if (evt.command_id === 'generalTaskNotice') {
          return;
        }

        let mainFormData = await handleSubmit();
        await defHttp.post({
          url: runProcessUrl,
          params: {
            data: mainFormData,
            runTaskBo: evt,
          },
        });

        if (props.taskId !== undefined) {
          window.parent.setvvisible();
        } else {
          closeTab();
        }
      };

      const handleViewChart = () => {
        const previewchartPath = window.approvalConfig?.previewchartPath || '';
        const view_url = `${previewchartPath}/ego-bpa-front/#/home/FlowDetail?uId=${processInstanceId.value}`;
        window.open(view_url, '_blank');
      };

      return {
        registerForm,
        formDisabled,
        formRef,
        handleSubmit,
        decisionClick,
        displayConfig,
        taskId,
        locale,
        processInstanceId,
        handleViewChart,
        appTheme,
      };
    },
  });
</script>
